package com.atstudying.mallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.atstudying.common.to.es.SkuEsModel;
import com.atstudying.mallsearch.config.MallESConfig;
import com.atstudying.mallsearch.constant.EsConstant;
import com.atstudying.mallsearch.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mr.zhneg
 * @create 2020-10-28-21:12
 */
@Service("ProductSaveService")
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService{
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        //保存到es
        //1：给es中建立索引。product：建立好映射关系

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model:skuEsModels){

            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());

            String s = JSON.toJSONString(model);
            indexRequest.source(s, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        //2：给es中保存数据
        //www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, MallESConfig.COMMON_OPTIONS);

        //查看是否有商品上架失败
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架成功：{}，返回数据：",collect,bulk.toString());

        return b;
    }
}
